#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void ChildWrite(int wfd)
{
    std::cout << "子进程wfd:" << wfd << std::endl;
    //char buff[1024];
    char c = 0;
    int cnt = 0;
    while (true)
    {
        sleep(1);
        //snprintf(buff, sizeof(buff), "第%d次:子进程写入\n", cnt++);
        ssize_t ret = write(wfd, &c, 1);
        (void)ret;
    }
}

void FatherRead(int rfd)
{
    std::cout << "父进程rfd:" << rfd << std::endl;
    //char buff[1024];
    char buff[1024*4*4];
    int cnt = 1;
    while (cnt--)
    {
        sleep(5);
        ssize_t ret = read(rfd, buff, sizeof(buff) - 1);
        buff[ret] = 0;
        std::cout << buff << std::endl;
        if (ret == 0)
        {
            std::cout << "写关闭了，读关闭" << std::endl;
            break;
        }
    }
}

int main()
{
    // 1.创建管道
    int pipefd[2] = {0};
    int ret = pipe(pipefd);
    if (ret == -1)
        exit(1);

    // 2.创建子进程，子进程写，父进程读
    pid_t pid = fork();
    if (pid < 0)
        exit(1);
    else if (pid == 0)
    {
        // 子进程
        close(pipefd[0]);
        ChildWrite(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }
    else
    {
        // 父进程
        close(pipefd[1]);
        FatherRead(pipefd[0]);
        close(pipefd[0]);
        int status;
        waitpid(pid, &status, 0);
        std::cout << "子进程 exit code:" << ((status >> 8) & 0xFF) << " exit signal:" << (status & 0x7F) << std::endl; 
    }

    return 0;
}